#!/usr/bin/perl -w
use strict;
use Includes;
use CGI qw/:standard *table *div -nosticky/;
use CGI::Pretty qw/ :html3 /;
use DBD::SQLite;

# Some variables 
my $c = new CGI;
my $SUCCESS = 0;
my ($password,$username,$hash) = (
		$c->param('password'),
		$c->param('username'),
		$c->param('hash')||'');
my $REASON = '';

# Some paths
my $DBFILE	 = "users.sql";

# Make the basic HTML and form 
print header(-type=>'text/html'),
			Includes::get_html("Create an Account"),
			div({id=>'main',class=>'rounded'},
					Includes::get_banner(),
					&status,
					($SUCCESS ? '' : &form)),
			end_html();

# Check to see if we succeeded 
if($SUCCESS){
	Includes::my_log('task1','info',"Account created: %s",$username);
}else{
	Includes::my_log('task1','debug',"Account creation failed: %s, %s",$username,$REASON);
}

### Functions ###

# Determine if the account was created 
sub status(){
	my $string;

	# Make sure this is a create attempt
	if(param && $c->param('action') eq 'Create'){
		use Switch;
		my $admin = $c->param('admin');
		Includes::my_log('task1','debug','Admin value: %s',$admin);
		my $results = &create_account($username,$password,$admin,$hash);
		switch($results){
			case	"BAD_UN"	{ $string = "Username must be 1-16 alphanumeric characters" }
			case	"BAD_PW"	{ $string = "Password must be 1-16 alphanumeric characters" }
			case	"NOT_HR"	{ $string = span("Only users with HR privileges can create users.",br,"Please contact your secretary") }
			case	19				{ $string = "An acccount with that name already exists" }	
			else						{ $string = "Account creation was successful"; $SUCCESS = 1}
		}
	}
	$REASON = $string;
	return $string ? div({id=>'status',class=>$SUCCESS?'success':'error'},$string) : '' ;
}

# Create the form
sub form(){
	return 
			start_form("GET"),
			fieldset(
				legend("Enter Account Information",
					p(label({for=>'username'},"Name"),textfield('username')),
					p(label({for=>'password'},"Password"),textfield('password')),
					hidden('admin','false'),
					p({class=>'submit'},submit('action','Create'))
					)
				),
			end_form,
			div({id=>'contact',class=>'center'},
				a({href=>'contact.cgi'},"Need to contact somebody?")),
		;
}

# Create an account
sub create_account($$$){
	my $retval = 0;
	my ($username,$password,$admin,$hash) = @_;
	#	Username can only contain alphanumerics
	if(!($username =~ /^[a-zA-Z0-9]{1,16}$/)){ 
		$retval = "BAD_UN";
	#	Password can only contain alphanumerics
	}elsif(!($password =~ /^[a-zA-Z0-9]{1,16}$/)){ 
		$retval = "BAD_PW";
	# Only admins with the cookie can create an account
	}elsif($hash ne Includes::get_hash()){
		$retval = "NOT_HR";	
	# All tests passed, try creating.  This can still fail on duplicate names
	}else{
		my $dbh = Includes::connect($DBFILE);
		my $sth = $dbh->prepare("INSERT INTO users VALUES (?,?,?)");
		$sth->bind_param(1,$username);
		$sth->bind_param(2,$password);
		$sth->bind_param(3,$admin eq 'true');
		my $rv = $sth->execute or die $sth->errstr;
		$retval = $DBI::err || 0;
	}
	return $retval;
}
